﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CSP.Common.Tools;
using CSP.Common.Web;
using CSP.Bll;
using CSP.Model.CSPBBS;
using CSP.Bll.IObjectBlls;
using System.Net;
using System.Configuration;
using CSP.Common.Factories;

namespace CSP.Web.UCenter
{
    public partial class Register : CSPPageBase
    {
        private string _createImageKey = "";

        private string _urlBack = "";

        /// <summary>
        /// 返回的URL
        /// </summary>
        protected string URLBack
        {
            get
            {
                return _urlBack;
            }
        }

        /// <summary>
        /// 创建验证码图片Key
        /// </summary>
        public string CreateImageKey
        {
            get
            {
                return _createImageKey;
            }

        }

        protected void Page_Load(object sender, EventArgs e)
        {
            //string aa = this.Txt_UserName.Name;
            if (Request[this.Txt_UserName.Name] != null && Request["checkname"] != null)
            {
                CheckUniqueByUserName(Request[this.Txt_UserName.Name].ToString());
            }

            if (Request["urlback"] != null)
            {
                _urlBack = Server.UrlEncode(Request["urlback"].ToString());
            }

            if (!IsPostBack)
            {
                InitRegister();
            }
        }

        /// <summary>
        /// 初始化业务
        /// </summary>
        private void InitRegister()
        {
            _createImageKey = CommonTool.GetGUIDForDateTime();
            Txt_CreateImageKey.Value = _createImageKey;
        }

        protected void BtnSubmit_Click(object sender, EventArgs e)
        {
            bool checkValue = CheckRegisterInfo();
            if (!checkValue)
            {
                return;
            }
            else
            {
                Member member = GetMemberByRegisterInfo();
                RegisterUser(member);
            }

        }

        /// <summary>
        /// 验证用户名是否重复
        /// </summary>
        protected void CheckUniqueByUserName(string userName)
        {
            bool checkValue = IsExsitByUserName(userName);

            Response.ClearContent();
            if (checkValue)
            {
                Response.Write("false");
            }
            else
            {
                Response.Write("true");
            }

            Response.End();
        }

        /// <summary>
        /// 注册用户
        /// </summary>
        /// <param name="member"></param>
        private void RegisterUser(Member member)
        {
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();
            try
            {
                using (IUserInfoBll userInfoBll = bllFactory.GetUserInfoBll())
                {
                    userInfoBll.AddUserInfo(member);
                    Session["UserName"] = member.UserName.Trim();
                    Session["Uid"] = member.Id;
                    CreateCookieByMember(member.Id, member.CommonMember.PassWord, DateTime.Now.AddHours(2));
                }
            }
            catch (Exception ex)
            {
                LoggerProvider.Error("注册失败", ex);
                FailRedirect("注册失败", "/UCenter/Register.aspx");
            }
            string url = "/";
            if (Request["urlback"] != null && Request["urlback"].ToString()!="")
            {
                url = Request["urlback"].ToString();
                Response.Redirect(url);
            }
            SuccessfullRedirect("恭喜您注册成功", url);
        }

        /// <summary>
        /// 根据注册信息获取用户基本信息
        /// </summary>
        /// <returns></returns>
        private Member GetMemberByRegisterInfo()
        {
            Member member = new Member();
            member.UserName = this.Txt_UserName.Value.Trim();
            member.PassWord = this.Txt_FirstPassWord.Value.Trim();
            //member.Email = this.Txt_Email.Value.Trim();
            //member.Salt = this.Txt_UserName.Value.Trim();
            member.LastLoginIp = 0;
            member.Regip = CommonTool.GetIP();
            return member;
        }

        /// <summary>
        /// 验证信息
        /// </summary>
        /// <returns></returns>
        private bool CheckRegisterInfo()
        {
            bool result = true;
            if (this.Txt_FirstPassWord.Value != this.Txt_ConfirmPassWord.Value)
            {
                Alert("两次输入的密码不一致,请重新输入");
                result = false;
            }

            string key = Txt_CreateImageKey.Value.Trim();
            string code = Txt_ValidationCode.Value.Trim();
            if (key != "" && result)
            {
                result = CommonTool.CheckImageByKeyAndImgCode(key, code);
                if (result == false)
                {
                    Alert("验证码错误");
                }
            }
            else if (key == "" && result)
            {
                Alert("验证码错误");
                result = false;
            }

            if (IsExsitByUserName(this.Txt_UserName.Value.Trim()) && result)
            {
                Alert("抱歉当前用户太抢手了,已经被人占用了,请换更换用户名~");
                result = false;
            }

            if (result == false)
            {

                InitRegister();
            }



            return result;
        }

        /// <summary>
        /// 用户名是否存在
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        private bool IsExsitByUserName(string userName)
        {
            bool result = false;
            CSPBllFactory bllFactory = CSPBllFactory.GetInstance();
            using (IUserInfoBll userInfoBll = bllFactory.GetUserInfoBll())
            {
                result = userInfoBll.IsExsitByUserName(userName.Trim());
            }
            return result;
        }

        /// <summary>
        /// 创建cookie
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="pwd"></param>
        /// <param name="expires"></param>
        private void CreateCookieByMember(int uid, string pwd, DateTime expires)
        {
            string saltkey = CommonTool.GenerateCode(8);
            string authKey = CommonTool.MD5(ConfigurationManager.AppSettings["AuthKey"].ToString() + saltkey);
            string cookieAuth = CommonTool.DiscuzAuthcodeEncode(pwd + "\t" + uid.ToString(), authKey);

            CookieFactory factory = CookieFactory.GetInstace();
            factory.Expires = expires;
            factory.SetCookie(this, "saltkey", saltkey);
            factory.SetCookie(this, "auth", cookieAuth);
        }
    }
}